package com.jason.fingerprint.ui;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.jason.fingerprint.AppContext;
import com.jason.fingerprint.R;
import com.jason.fingerprint.adapter.RecorderAdapter;
import com.jason.fingerprint.beans.SponsorInfo;
import com.jason.fingerprint.beans.WorkVisitBean;
import com.jason.fingerprint.beans.ui.ImageOrAudioBean;
import com.jason.fingerprint.beans.ui.SoundBean;
import com.jason.fingerprint.common.SoundRecorder;
import com.jason.fingerprint.configs.DataConfig;
import com.jason.fingerprint.logic.UploadToTempSyncLogic;
import com.jason.fingerprint.widget.PullToRefreshListView;
import org.kymjs.aframe.database.KJDB;
import org.kymjs.aframe.ui.BindView;
import org.kymjs.aframe.ui.KJActivityManager;
import org.kymjs.aframe.ui.activity.BaseActivity;
import org.kymjs.aframe.utils.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: RecorderManagerActivity
 * @Description: 录音管理
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2015年10月20日16:30:44
 */
public class RecorderManagerActivity extends BaseActivity {

    private static final String TAG = RecorderManagerActivity.class.getSimpleName();
    public static final String INTENT_RECORDER_SIGN_DETAIL = "intent_recorder_sign_detail";//集中活动，教育
    public static final String INTENT_RECORDER_WORK_VISIT = "intent_recorder_work_visit";//工作走访
    public static final String KEY_SOURCE = "key_source";//来源数据信息
    public static final String KEY_RECORD_COUNT = "key_Record_count";//录音的个数

    @BindView(id = R.id.header_back,click = true)
    private Button mBackButton;
    @BindView(id = R.id.header_title)
    private TextView mTitleTextView;
    @BindView(id = R.id.header_complete,click = true)
    private Button mStartButton;

    private String mSponsorType; // 活动类型（0-集中教育 1-集中劳动 2-个别教育 3-个别劳动）
    private List<ImageOrAudioBean> mImageOrAudioBeans = new ArrayList<ImageOrAudioBean>();
    private RecorderAdapter mRecorderAdapter;
    private PullToRefreshListView mListView;
    private String mAction;
    private SponsorInfo mSponsorInfo;
    private WorkVisitBean mWorkVisitBean;
    private int mCount;
    private SoundBean mSoundBean;
    private int mServiceId;
    private KJDB mKjdb;

    private int mSourceCount;

    @Override
    public void setRootView() {
        setContentView(R.layout.activity_recorder_manager);
    }

    @Override
    protected void initWidget() {
        super.initWidget();
        mStartButton.setText("录音");
        mListView = (PullToRefreshListView) findViewById(R.id.recorder_listview);
    }

    // 查询数据库
    private List<ImageOrAudioBean> loadData() {
        StringBuilder where = new StringBuilder();
        if (!StringUtils.isEmpty(mSponsorType)) {
            if (mSponsorType.equals(DataConfig.REGISTER_TYPE_2)
                    || mSponsorType.equals(DataConfig.REGISTER_TYPE_3)) {
                mServiceId = UploadToTempSyncLogic.SERVICE.SERVICE_COMMUNITY_SINGLE;
            }else {
                mServiceId = UploadToTempSyncLogic.SERVICE.SERVICE_COMMUNITY_IMPLODE;
            }
            where.append("sponsorType = '");
            where.append(mSponsorType);
            where.append("'");
            where.append(" and ");
        }
        where.append("serviceId = ");
        where.append(mServiceId);
        where.append(" and state = 1");
        if (mServiceId == UploadToTempSyncLogic.SERVICE.SERVICE_WORK_VISIT){
            where.append("parentId = '");
            where.append(mWorkVisitBean.getId());
            where.append("'");
        }
        Log.i(TAG, "---execute--where:" + where.toString());
        mImageOrAudioBeans = mKjdb.findAllByWhere(ImageOrAudioBean.class,
                where.toString());
        if (mImageOrAudioBeans != null && mImageOrAudioBeans.isEmpty()){
            mSourceCount = mImageOrAudioBeans.size();
        }
        return mImageOrAudioBeans;
    }

    @Override
    protected void initData() {
        super.initData();
        mKjdb = AppContext.getInstance().getKjdb();
        mTitleTextView.setText("录音管理");
        Intent intent = getIntent();
        if (intent != null) {
            mSoundBean = (SoundBean) intent.getSerializableExtra(KEY_SOURCE);
            mAction = intent.getAction();
            mCount = intent.getIntExtra(KEY_RECORD_COUNT, 0);

            if (INTENT_RECORDER_SIGN_DETAIL.equals(mAction)){
                mSponsorInfo = (SponsorInfo) mSoundBean.getSource();
            }else if (INTENT_RECORDER_WORK_VISIT.equals(mAction)){
                mWorkVisitBean = (WorkVisitBean) mSoundBean.getSource();
            }
            mSponsorType = mSoundBean.registerType;
            if (loadData() != null){
                mRecorderAdapter = new RecorderAdapter(this,mImageOrAudioBeans);
                mListView.setAdapter(mRecorderAdapter);
            }
            if (mSourceCount >= mCount){
                Toast.makeText(RecorderManagerActivity.this,"已经录音完毕",Toast.LENGTH_SHORT).show();
                mStartButton.setVisibility(View.GONE);
            }else{
                mStartButton.setVisibility(View.VISIBLE);
            }
            if (INTENT_RECORDER_SIGN_DETAIL.equals(mAction)){

            }else if (INTENT_RECORDER_WORK_VISIT.equals(mAction)){

            }
        }
    }

    @Override
    public void widgetClick(View v) {
        super.widgetClick(v);
        switch (v.getId()) {
            case R.id.header_back:
                KJActivityManager.create().finishActivity(RecorderManagerActivity.this);
                break;
            case R.id.header_complete:
                //TODO 开启录音，判断当前录音的状态，是否处于录音中，则停止保存，开启录音
                startRecorder();

                break;

            default:
                break;
        }
    }

    private void startRecorder(){
        int state = HomeActivity.mHomeActivity.mService.getRecordState();

        boolean ongoing = state == SoundRecorder.STATE_RECORDING
                || state == SoundRecorder.STATE_PLAYING;
        if (ongoing){
            new AlertDialog.Builder(RecorderManagerActivity.this).setTitle("录音提示")
                    .setMessage("录音正在使用，是否继续录音？").setCancelable(true)
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            //TODO 保存
                            save();
                            //TODO 开始
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    start();
                                }
                            },500l);
                            dialog.dismiss();
                            KJActivityManager.create().finishActivity(RecorderManagerActivity.this);
                        }

                    }).setNegativeButton("取消", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {

                    dialog.dismiss();
                }

            }).create().show();
        }else{
            //TODO 开始
            start();
        }

    }

    private void save(){
        Intent intent = new Intent(HomeActivity.INTENT_RECORD_STOP);
        intent.putExtra(HomeActivity.KEY_RECORD_SOUND,mSoundBean);
        sendBroadcast(intent);
    }

    private void start(){
        Intent intent = new Intent(HomeActivity.INTENT_RECORD_START);
        intent.putExtra(HomeActivity.KEY_RECORD_SOUND,mSoundBean);
        sendBroadcast(intent);
        KJActivityManager.create().finishActivity(RecorderManagerActivity.this);
    }

    public void deleteRecorder(ImageOrAudioBean bean){
        if (bean != null){
            mKjdb.deleteById(ImageOrAudioBean.class,bean.getId());
            if (loadData() != null){
                mRecorderAdapter = new RecorderAdapter(this,mImageOrAudioBeans);
            }else{
                mRecorderAdapter = new RecorderAdapter(this,new ArrayList<ImageOrAudioBean>());
            }
            mListView.setAdapter(mRecorderAdapter);
        }
    }
}
